package com.edu.yunnote;

import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edu.yunnote.dto.Note;
import com.edu.yunnote.dto.WebResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {


    private ListView lv_note;
    private NoteAdapter noteAdapter;
    private Context context;
    private SharedPreferences sharedPreferences;

    //构造菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //动态向菜单中添加选项
        //meu.add(menu组ID,menu的ID,上级menu的ID,需要显示的文本内容)
        //menu.add(Menu.NONE, 123, Menu.NONE, "急急急");

        //菜单填充
        getMenuInflater().inflate(R.menu.main,menu);
        //使菜单显示出来
        return true;
    }
    //为每个菜单选项添加监听事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_logout:
                //注销
                SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putInt("userId",0);
                editor.putString("username", null);
                editor.putString("password", null);
                editor.putString("tel", null);
                editor.commit();
                Toast.makeText(this,"退出登陆", Toast.LENGTH_SHORT).show();
                gotoActivity(LoginActivity.class);
                break;
            case R.id.menu_refresh:
                //刷新当前页面
                Intent intentRefresh = new Intent(MainActivity.this, MainActivity.class);
                startActivity(intentRefresh);
                //Toast.makeText(this,"刷新", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu_add_note:
                Intent intent = new Intent(MainActivity.this, com.edu.yunnote.EditActivity.class);
                startActivity(intent);
                //Toast.makeText(this,"添加笔记", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }
    public void init(){

        lv_note = findViewById(R.id.lv_note);

        this.context = this;
        //请求用户的笔记
        String url = getString(R.string.url) + "/noteServlet";
        Map<String, Object> map = new HashMap<String, Object>();
        //获取SharedPreferences中的用户信息
        sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userId", 0);//(key,若无数据需要赋的值)
        map.put("userId",userId);
        map.put("act", "list");
        try {
            postJSON(url , map , 1);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("LOOKUP  postJSON : ", e.getMessage());
        }


        //单击查询
        lv_note.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Note note = (Note)lv_note.getItemAtPosition(position);
            Intent intent = new Intent(MainActivity.this,ShowActivity.class);
            intent.putExtra("noteId",note.getNoteId().toString());
            intent.putExtra("noteTitle",note.getNoteTitle());
            intent.putExtra("noteContent",note.getNoteContent());
            intent.putExtra("noteTime",note.getNoteTime());
            startActivity(intent);
            }
        });


        //双击删除
        lv_note.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final Note note = (Note)lv_note.getItemAtPosition(position);
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("提示框")
                        .setMessage("是否删除?")
                        .setPositiveButton("yes",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //删除用户的笔记
                                        String url = getString(R.string.url) + "/noteServlet";
                                        Map<String, Object> map = new HashMap<String, Object>();
                                        int noteId = note.getNoteId();
                                        map.put("noteId",noteId);
                                        map.put("act", "delete");
                                        try {
                                            postJSON(url , map , 2);
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                            Log.d("LOOKUP  postJSON : ", e.getMessage());
                                        }

                                    }
                                })
                        .setNegativeButton("no",null).show();
                return true;
            }
        });
    }


    /**
     * yunNote的适配器
     *
     */
    class NoteAdapter extends BaseAdapter{

        private Vector<Note> notesList;
        private Context context;
        private int layoutId;

        public NoteAdapter(Vector<Note> notesList, Context context, int layoutId) {
            this.notesList = notesList;
            this.context = context;
            this.layoutId = layoutId;
        }

        @Override
        public int getCount() {
            if (notesList != null && notesList.size() > 0)
                return notesList.size();
            else
                return 0;
        }

        @Override
        public Object getItem(int position) {
            if (notesList != null && notesList.size() > 0)
                return notesList.get(position);
            else
                return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(
                        getApplicationContext()).inflate(R.layout.note_item, parent,
                        false);
                viewHolder = new ViewHolder();
                viewHolder.title = (TextView) convertView.findViewById(R.id.tv_title);
                viewHolder.content = convertView.findViewById(R.id.tv_content);
                viewHolder.time = (TextView) convertView.findViewById(R.id.tv_time);
                viewHolder.noteId = (TextView) convertView.findViewById(R.id.tv_note_id);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            String title = notesList.get(position).getNoteTitle();
            String content = notesList.get(position).getNoteContent();
            String noteId = notesList.get(position).getNoteId().toString();

            viewHolder.title.setText(title);
            viewHolder.content.setText(content);
            viewHolder.time.setText(notesList.get(position).getNoteTime().toString());
            viewHolder.noteId.setText(noteId);

            return convertView;
        }

        public void removeItem(int position){
            this.notesList.remove(position);
        }
    }


    class ViewHolder{
        TextView title;
        TextView content;
        TextView time;
        TextView noteId;
    }

    /**
     * ==============================OKHTTP请求 ==============================================
     */
    /**
     * 当前类的消息机制 手柄，句柄
     */
    private Handler handler = new Handler(new Handler.Callback() { //消息回调
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public boolean handleMessage(Message msg) {
            Map<String, Object> parmaData = new HashMap<String, Object>();
            WebResponse webResponse;
            String res = null;
            switch(msg.what){
                case 1:     //获取记事本列表
                    res = msg.obj.toString();
                    Log.d("LOOKUP -- msg.what : ", res); //请求数据在msg.obj.toString()中

                    if(res.indexOf("HTTP Status") != -1){
                        Toast.makeText(MainActivity.this,"网络请求出错" ,Toast.LENGTH_SHORT).show();
                        break;
                    }

                    //把json数据转换成webResponse
                    webResponse = new Gson().fromJson(res, WebResponse.class);
                    Log.d("LOOKUP webResponse : ", webResponse.toString());

                    if(webResponse.getStatusCode() == 200) {
                        Toast.makeText(MainActivity.this,webResponse.getStatusMsg() ,Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this,webResponse.getStatusMsg() ,Toast.LENGTH_LONG).show();
                        break;
                    }

                    //把json数据转换成map
                    parmaData = new HashMap<String, Object>();
                    parmaData = (Map<String, Object>) JSON.parse(JSONObject.toJSON(webResponse.getData()).toString());

                    //把json数据转换成user
                    Vector<Note> noteList = new Gson().fromJson(JSONObject.toJSON(parmaData.get("NoteList")).toString(),Vector.class);
                    Note nn ;
                    for( int i = 0 ; i < noteList.size() ; i++ ) {
                        nn = new Note();
                        nn = new Gson().fromJson(JSONObject.toJSON(noteList.get(i)).toString() , Note.class);
                        noteList.set(i, nn);
                        System.out.println(noteList.get(i));
                    }

                    noteAdapter = new NoteAdapter(noteList, context, R.layout.note_item);
                    lv_note.setAdapter(noteAdapter);


                    break;
                case 2:     //删除笔记
                    res = msg.obj.toString();
                    Log.d("LOOKUP -- msg.what : ", res); //请求数据在msg.obj.toString()中

                    if(res.indexOf("HTTP Status") != -1)
                        break;
                    //把json数据转换成webResponse
                    webResponse = new Gson().fromJson(res, WebResponse.class);
                    Log.d("LOOKUP webResponse : ", webResponse.toString());

                    if(webResponse.getStatusCode() == 200) {
                        Toast.makeText(MainActivity.this,webResponse.getStatusMsg() ,Toast.LENGTH_SHORT).show();
                        //刷新当前页面
                        Intent intent = new Intent(MainActivity.this, MainActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(MainActivity.this,webResponse.getStatusMsg() ,Toast.LENGTH_LONG).show();
                        break;
                    }

                    break;
                default:
                    Toast.makeText(MainActivity.this,"网络服务器连接失败" ,Toast.LENGTH_SHORT).show();
                    break;
            }
            return true;
        }
    });

    /**
     *
     * @param url 请求地址
     * @param map 转化成 json字符串作为请求参数
     * @param msgWhat 发送消息的编号，用于接收消息时判断
     * @return
     * @throws IOException
     */
    public void postJSON(String url , Map<String, Object> map , final Integer msgWhat) throws IOException {

        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String json = gson.toJson(map);
        OkHttpClient client = new OkHttpClient();
        MediaType JSON   = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call  = client.newCall(request);
        call.enqueue(new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("LOOKUP","请求失败");
                Log.d("LOOKUP",e.getMessage());
                Message msg = new Message();
                msg.obj = "网络服务器连接失败";
                msg.what = 0;
                handler.sendMessage(msg);	//发送消息到句柄

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg = new Message();
                msg.obj = response.body().string();
                msg.what = msgWhat;
                handler.sendMessage(msg);	//发送消息到句柄
            }
        });
    }
    /**
     * ==============================OKHTTP请求 end==============================================
     */





    /**
     * intent跳转页面，不能返回之前页面
     * @param B
     */
    private void gotoActivity(Class B){
        Intent intent=new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(MainActivity.this, B);
        startActivity(intent);
    }

    private long exitTime = 0;
    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            //彻底关闭整个APP
            int currentVersion = android.os.Build.VERSION.SDK_INT;
            if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                System.exit(0);
            } else {// android2.1
                ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                am.restartPackage(getPackageName());
            }
        }
    }





}


